﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using Castle.DynamicProxy;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace AopIocExtensions
{
    public static class AopExtension
    {
        public static void AddAopService<T>(this ContainerBuilder builder, Type[] types, string serviceAssemblyName) where T : IInterceptor
        {
            //注册拦截器，同步异步都要
            foreach (var type in types)
                builder.RegisterType(type).AsSelf();

            //builder.RegisterType<T>().AsSelf();
            //builder.RegisterType<LogInterceptorAsync>().AsSelf();

            //注册业务层，同时对业务层的方法进行拦截
            builder.RegisterAssemblyTypes(Assembly.Load(serviceAssemblyName))
                .AsImplementedInterfaces().InstancePerLifetimeScope()
                .EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
                .InterceptedBy(types)//这里只有同步的，因为异步方法拦截器还是先走同步拦截器 
                ;

            //业务层注册拦截器也可以使用[Intercept(typeof(LogInterceptor))]加在类上，但是上面的方法比较好，没有侵入性
        }
    }
}